local FileHandle = {}


function FileHandle:MapFromJsonLine(path)
    local file = io.open(path, "r")
    if not file then
        io.open(path, "w"):close()
        return {}
    end
    local t = {}
    local ll_func = io.lines(path)
    for line in ll_func do
        local re, data = xpcall(
            function() return json.decode(line) end, 
            function() end
        )
        if type(data)=="table" then
            local key = data.id
            if key then
                data.id = nil
                t[key] = data
            end
        end
    end
    return t
end

function FileHandle:MapToJsonLine(path, t)
    local file = io.open(path, "w")
    local str = ""
    for key,l in pairs(t)do
        l.id = key
        str = str..json.encode(l).."\n"
    end
    file:write(str)
    file:close()
end

function FileHandle:ListFromJsonLine(path)
    local file = io.open(path, "r")
    if not file then
        io.open(path, "w"):close()
        return {}
    end
    local t = {}
    local ll_func = io.lines(path)
    for line in ll_func do
        local re, data = xpcall(
            function() return json.decode(line) end, 
            function() end
        )
        if re then
            table.insert(t, data)
        end
    end
    return t
end

function FileHandle:ListToJsonLine(path, t)
    local file = io.open(path, "w")
    local str = ""
    for _,l in pairs(t)do
        str = str..json.encode(l).."\n"
    end
    file:write(str)
    file:close()
end


function FileHandle:LoadTableFromFile(path)
    local file = io.open(path, "r")
    if not file then
        file = io.open(path, "w")
        file:close()
        return {}
    end
    local t = {}
    local ll_func = io.lines(path)
    for line in ll_func do
        table.insert(t, line)
    end
    return t
end


local log_path = "ShroomCakeTestLog.txt"
function FileHandle:LogAddFile(...)
    local str = table.concat({...}, " ")
    local data = self:LoadTableFromFile(log_path)
    local file = io.open(log_path, "w")
    file:write(table.concat(data, "\n"))
    file:write("\n"..os.date().."  "..str)
    file:close()
    print(str)
end

return FileHandle
